<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>分类: 技术教程 | 小小程序员</title><meta name="author" content="十一星野"><meta name="copyright" content="十一星野"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="本文主要讲解 mall 通过整合 SpringSecurity 和 JWT 实现后台用户的登录和授权功能，同时改造 Swagger-UI 的配置使其可以自动记住登录令牌进行发送。  #👍 相关视频教程mall整合Spring Security和JWT实现认证和授权open in new window #项目使用框架介绍#SpringSecurity SpringSecurity是一个强大的可高">
<meta property="og:type" content="article">
<meta property="og:title" content="mall整合SpringSecurity和JWT实现认证和授权（一）">
<meta property="og:url" content="https://ko25891wan.gitlab.io/2024/01/52c2363b5c0f.html">
<meta property="og:site_name" content="小小程序员">
<meta property="og:description" content="本文主要讲解 mall 通过整合 SpringSecurity 和 JWT 实现后台用户的登录和授权功能，同时改造 Swagger-UI 的配置使其可以自动记住登录令牌进行发送。  #👍 相关视频教程mall整合Spring Security和JWT实现认证和授权open in new window #项目使用框架介绍#SpringSecurity SpringSecurity是一个强大的可高">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png">
<meta property="article:published_time" content="2024-01-21T09:26:57.000Z">
<meta property="article:modified_time" content="2024-02-02T15:05:32.522Z">
<meta property="article:author" content="十一星野">
<meta property="article:tag" content="宅男,热血">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://ko25891wan.gitlab.io/2024/01/52c2363b5c0f.html"><link rel="preconnect" href="//fastly.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":1,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.staticfile.org/egjs-infinitegrid/4.11.0/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '分类: 技术教程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2024-02-02 23:05:32'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="小小程序员"><span class="site-name">小小程序员</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/md_editor/"><i class="fa-fw fas fa-pen"></i><span> MDEditor_my</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">mall整合SpringSecurity和JWT实现认证和授权（一）</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-01-21T09:26:57.000Z" title="发表于 2024-01-21 17:26:57">2024-01-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2024-02-02T15:05:32.522Z" title="更新于 2024-02-02 23:05:32">2024-02-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/">技术教程</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/">mall</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%8A%80%E6%9C%AF%E6%95%99%E7%A8%8B/mall/%E6%9E%B6%E6%9E%84%E7%AF%87/">架构篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="mall整合SpringSecurity和JWT实现认证和授权（一）"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><blockquote>
<p>本文主要讲解 mall 通过整合 SpringSecurity 和 JWT 实现后台用户的登录和授权功能，同时改造 Swagger-UI 的配置使其可以自动记住登录令牌进行发送。</p>
</blockquote>
<h2 id="👍-相关视频教程"><a href="#👍-相关视频教程" class="headerlink" title="#👍 相关视频教程"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B">#</a>👍 相关视频教程</h2><p><a target="_blank" rel="noopener" href="https://t.zsxq.com/0et6nCQmM">mall整合Spring Security和JWT实现认证和授权open in new window</a></p>
<h2 id="项目使用框架介绍"><a href="#项目使用框架介绍" class="headerlink" title="#项目使用框架介绍"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E9%A1%B9%E7%9B%AE%E4%BD%BF%E7%94%A8%E6%A1%86%E6%9E%B6%E4%BB%8B%E7%BB%8D">#</a>项目使用框架介绍</h2><h3 id="SpringSecurity"><a href="#SpringSecurity" class="headerlink" title="#SpringSecurity"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#springsecurity">#</a>SpringSecurity</h3><blockquote>
<p>SpringSecurity是一个强大的可高度定制的认证和授权框架，对于Spring应用来说它是一套Web安全标准。SpringSecurity注重于为Java应用提供认证和授权功能，像所有的Spring项目一样，它对自定义需求具有强大的扩展性。</p>
</blockquote>
<h3 id="JWT"><a href="#JWT" class="headerlink" title="#JWT"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#jwt">#</a>JWT</h3><blockquote>
<p>JWT是JSON WEB TOKEN的缩写，它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象，由于使用了数字签名，所以是可信任和安全的。</p>
</blockquote>
<h4 id="JWT的组成"><a href="#JWT的组成" class="headerlink" title="#JWT的组成"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#jwt%E7%9A%84%E7%BB%84%E6%88%90">#</a>JWT的组成</h4><ul>
<li>JWT token的格式：header.payload.signature</li>
<li>header中用于存放签名的生成算法</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;alg&quot;: &quot;HS512&quot;&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>payload中用于存放用户名、token的生成时间和过期时间</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&quot;sub&quot;:&quot;admin&quot;,&quot;created&quot;:1489079981393,&quot;exp&quot;:1489684781&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>signature为以header和payload生成的签名，一旦header和payload被篡改，验证将失败</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">//secret为加密算法的密钥</span><br><span class="line">String signature = HMACSHA512(base64UrlEncode(header) + &quot;.&quot; +base64UrlEncode(payload),secret)</span><br></pre></td></tr></table></figure>

<h4 id="JWT实例"><a href="#JWT实例" class="headerlink" title="#JWT实例"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#jwt%E5%AE%9E%E4%BE%8B">#</a>JWT实例</h4><p>这是一个JWT的字符串</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE1NTY3NzkxMjUzMDksImV4cCI6MTU1NzM4MzkyNX0.d-iki0193X0bBOETf2UN3r3PotNIEAV7mzIxxeI5IxFyzzkOZxS0PGfF_SK6wxCv2K8S0cZjMkv6b5bCqc0VBw</span><br></pre></td></tr></table></figure>

<p>可以在该网站上获得解析结果：<a target="_blank" rel="noopener" href="https://jwt.io/">https://jwt.io/</a> <img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/obsition/2024-02-02_23:05:29_arch_screen_13-fc3ff0ff.png"></p>
<h4 id="JWT实现认证和授权的原理"><a href="#JWT实现认证和授权的原理" class="headerlink" title="#JWT实现认证和授权的原理"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#jwt%E5%AE%9E%E7%8E%B0%E8%AE%A4%E8%AF%81%E5%92%8C%E6%8E%88%E6%9D%83%E7%9A%84%E5%8E%9F%E7%90%86">#</a>JWT实现认证和授权的原理</h4><ul>
<li>用户调用登录接口，登录成功后获取到JWT的token；</li>
<li>之后用户每次调用接口都在http的header中添加一个叫Authorization的头，值为JWT的token；</li>
<li>后台程序通过对Authorization头中信息的解码及数字签名校验来获取其中的用户信息，从而实现认证和授权。</li>
</ul>
<h3 id="Hutool"><a href="#Hutool" class="headerlink" title="#Hutool"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#hutool">#</a>Hutool</h3><blockquote>
<p>Hutool是一个丰富的Java开源工具包,它帮助我们简化每一行代码，减少每一个方法，mall项目采用了此工具包。</p>
</blockquote>
<h2 id="项目使用表说明"><a href="#项目使用表说明" class="headerlink" title="#项目使用表说明"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E9%A1%B9%E7%9B%AE%E4%BD%BF%E7%94%A8%E8%A1%A8%E8%AF%B4%E6%98%8E">#</a>项目使用表说明</h2><ul>
<li><code>ums_admin</code>：后台用户表</li>
<li><code>ums_role</code>：后台用户角色表</li>
<li><code>ums_permission</code>：后台用户权限表</li>
<li><code>ums_admin_role_relation</code>：后台用户和角色关系表，用户与角色是多对多关系</li>
<li><code>ums_role_permission_relation</code>：后台用户角色和权限关系表，角色与权限是多对多关系</li>
<li><code>ums_admin_permission_relation</code>：后台用户和权限关系表(除角色中定义的权限以外的加减权限)，加权限是指用户比角色多出的权限，减权限是指用户比角色少的权限</li>
</ul>
<h2 id="整合SpringSecurity及JWT"><a href="#整合SpringSecurity及JWT" class="headerlink" title="#整合SpringSecurity及JWT"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%95%B4%E5%90%88springsecurity%E5%8F%8Ajwt">#</a>整合SpringSecurity及JWT</h2><h3 id="在pom-xml中添加项目依赖"><a href="#在pom-xml中添加项目依赖" class="headerlink" title="#在pom.xml中添加项目依赖"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E5%9C%A8pom-xml%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%A1%B9%E7%9B%AE%E4%BE%9D%E8%B5%96">#</a>在pom.xml中添加项目依赖</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&lt;!--SpringSecurity依赖配置--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;!--Hutool Java工具包--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;cn.hutool&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;hutool-all&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;4.5.7&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;!--JWT(Json Web Token)登录支持--&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;jjwt&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;0.9.0&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<h3 id="添加JWT-token的工具类"><a href="#添加JWT-token的工具类" class="headerlink" title="#添加JWT token的工具类"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0jwt-token%E7%9A%84%E5%B7%A5%E5%85%B7%E7%B1%BB">#</a>添加JWT token的工具类</h3><blockquote>
<p>用于生成和解析JWT token的工具类</p>
</blockquote>
<p>相关方法说明：</p>
<ul>
<li>generateToken(UserDetails userDetails) :用于根据登录用户信息生成token</li>
<li>getUserNameFromToken(String token)：从token中获取登录用户的信息</li>
<li>validateToken(String token, UserDetails userDetails)：判断token是否还有效</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.common.utils;</span><br><span class="line"></span><br><span class="line">import io.jsonwebtoken.Claims;</span><br><span class="line">import io.jsonwebtoken.Jwts;</span><br><span class="line">import io.jsonwebtoken.SignatureAlgorithm;</span><br><span class="line">import org.slf4j.Logger;</span><br><span class="line">import org.slf4j.LoggerFactory;</span><br><span class="line">import org.springframework.beans.factory.annotation.Value;</span><br><span class="line">import org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line">import org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line">import java.util.Date;</span><br><span class="line">import java.util.HashMap;</span><br><span class="line">import java.util.Map;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * JwtToken生成的工具类</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">public class JwtTokenUtil &#123;</span><br><span class="line">    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);</span><br><span class="line">    private static final String CLAIM_KEY_USERNAME = &quot;sub&quot;;</span><br><span class="line">    private static final String CLAIM_KEY_CREATED = &quot;created&quot;;</span><br><span class="line">    @Value(&quot;$&#123;jwt.secret&#125;&quot;)</span><br><span class="line">    private String secret;</span><br><span class="line">    @Value(&quot;$&#123;jwt.expiration&#125;&quot;)</span><br><span class="line">    private Long expiration;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据负责生成JWT的token</span><br><span class="line">     */</span><br><span class="line">    private String generateToken(Map&lt;String, Object&gt; claims) &#123;</span><br><span class="line">        return Jwts.builder()</span><br><span class="line">                .setClaims(claims)</span><br><span class="line">                .setExpiration(generateExpirationDate())</span><br><span class="line">                .signWith(SignatureAlgorithm.HS512, secret)</span><br><span class="line">                .compact();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从token中获取JWT中的负载</span><br><span class="line">     */</span><br><span class="line">    private Claims getClaimsFromToken(String token) &#123;</span><br><span class="line">        Claims claims = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            claims = Jwts.parser()</span><br><span class="line">                    .setSigningKey(secret)</span><br><span class="line">                    .parseClaimsJws(token)</span><br><span class="line">                    .getBody();</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            LOGGER.info(&quot;JWT格式验证失败:&#123;&#125;&quot;,token);</span><br><span class="line">        &#125;</span><br><span class="line">        return claims;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成token的过期时间</span><br><span class="line">     */</span><br><span class="line">    private Date generateExpirationDate() &#123;</span><br><span class="line">        return new Date(System.currentTimeMillis() + expiration * 1000);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从token中获取登录用户名</span><br><span class="line">     */</span><br><span class="line">    public String getUserNameFromToken(String token) &#123;</span><br><span class="line">        String username;</span><br><span class="line">        try &#123;</span><br><span class="line">            Claims claims = getClaimsFromToken(token);</span><br><span class="line">            username =  claims.getSubject();</span><br><span class="line">        &#125; catch (Exception e) &#123;</span><br><span class="line">            username = null;</span><br><span class="line">        &#125;</span><br><span class="line">        return username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 验证token是否还有效</span><br><span class="line">     *</span><br><span class="line">     * @param token       客户端传入的token</span><br><span class="line">     * @param userDetails 从数据库中查询出来的用户信息</span><br><span class="line">     */</span><br><span class="line">    public boolean validateToken(String token, UserDetails userDetails) &#123;</span><br><span class="line">        String username = getUserNameFromToken(token);</span><br><span class="line">        return username.equals(userDetails.getUsername()) &amp;&amp; !isTokenExpired(token);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断token是否已经失效</span><br><span class="line">     */</span><br><span class="line">    private boolean isTokenExpired(String token) &#123;</span><br><span class="line">        Date expiredDate = getExpiredDateFromToken(token);</span><br><span class="line">        return expiredDate.before(new Date());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 从token中获取过期时间</span><br><span class="line">     */</span><br><span class="line">    private Date getExpiredDateFromToken(String token) &#123;</span><br><span class="line">        Claims claims = getClaimsFromToken(token);</span><br><span class="line">        return claims.getExpiration();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 根据用户信息生成token</span><br><span class="line">     */</span><br><span class="line">    public String generateToken(UserDetails userDetails) &#123;</span><br><span class="line">        Map&lt;String, Object&gt; claims = new HashMap&lt;&gt;();</span><br><span class="line">        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());</span><br><span class="line">        claims.put(CLAIM_KEY_CREATED, new Date());</span><br><span class="line">        return generateToken(claims);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断token是否可以被刷新</span><br><span class="line">     */</span><br><span class="line">    public boolean canRefresh(String token) &#123;</span><br><span class="line">        return !isTokenExpired(token);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 刷新token</span><br><span class="line">     */</span><br><span class="line">    public String refreshToken(String token) &#123;</span><br><span class="line">        Claims claims = getClaimsFromToken(token);</span><br><span class="line">        claims.put(CLAIM_KEY_CREATED, new Date());</span><br><span class="line">        return generateToken(claims);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="添加SpringSecurity的配置类"><a href="#添加SpringSecurity的配置类" class="headerlink" title="#添加SpringSecurity的配置类"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0springsecurity%E7%9A%84%E9%85%8D%E7%BD%AE%E7%B1%BB">#</a>添加SpringSecurity的配置类</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.config;</span><br><span class="line"></span><br><span class="line">import com.macro.mall.tiny.component.JwtAuthenticationTokenFilter;</span><br><span class="line">import com.macro.mall.tiny.component.RestAuthenticationEntryPoint;</span><br><span class="line">import com.macro.mall.tiny.component.RestfulAccessDeniedHandler;</span><br><span class="line">import com.macro.mall.tiny.dto.AdminUserDetails;</span><br><span class="line">import com.macro.mall.tiny.mbg.model.UmsAdmin;</span><br><span class="line">import com.macro.mall.tiny.mbg.model.UmsPermission;</span><br><span class="line">import com.macro.mall.tiny.service.UmsAdminService;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.context.annotation.Bean;</span><br><span class="line">import org.springframework.context.annotation.Configuration;</span><br><span class="line">import org.springframework.http.HttpMethod;</span><br><span class="line">import org.springframework.security.authentication.AuthenticationManager;</span><br><span class="line">import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;</span><br><span class="line">import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;</span><br><span class="line">import org.springframework.security.config.annotation.web.builders.HttpSecurity;</span><br><span class="line">import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;</span><br><span class="line">import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;</span><br><span class="line">import org.springframework.security.config.http.SessionCreationPolicy;</span><br><span class="line">import org.springframework.security.core.userdetails.UserDetailsService;</span><br><span class="line">import org.springframework.security.core.userdetails.UsernameNotFoundException;</span><br><span class="line">import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;</span><br><span class="line">import org.springframework.security.crypto.password.PasswordEncoder;</span><br><span class="line">import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;</span><br><span class="line"></span><br><span class="line">import java.util.List;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * SpringSecurity的配置</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">@EnableWebSecurity</span><br><span class="line">@EnableGlobalMethodSecurity(prePostEnabled=true)</span><br><span class="line">public class SecurityConfig extends WebSecurityConfigurerAdapter &#123;</span><br><span class="line">    @Autowired</span><br><span class="line">    private UmsAdminService adminService;</span><br><span class="line">    @Autowired</span><br><span class="line">    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;</span><br><span class="line">    @Autowired</span><br><span class="line">    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void configure(HttpSecurity httpSecurity) throws Exception &#123;</span><br><span class="line">        httpSecurity.csrf()// 由于使用的是JWT，我们这里不需要csrf</span><br><span class="line">                .disable()</span><br><span class="line">                .sessionManagement()// 基于token，所以不需要session</span><br><span class="line">                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)</span><br><span class="line">                .and()</span><br><span class="line">                .authorizeRequests()</span><br><span class="line">                .antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问</span><br><span class="line">                        &quot;/&quot;,</span><br><span class="line">                        &quot;/*.html&quot;,</span><br><span class="line">                        &quot;/favicon.ico&quot;,</span><br><span class="line">                        &quot;/**/*.html&quot;,</span><br><span class="line">                        &quot;/**/*.css&quot;,</span><br><span class="line">                        &quot;/**/*.js&quot;,</span><br><span class="line">                        &quot;/swagger-resources/**&quot;,</span><br><span class="line">                        &quot;/v2/api-docs/**&quot;</span><br><span class="line">                )</span><br><span class="line">                .permitAll()</span><br><span class="line">                .antMatchers(&quot;/admin/login&quot;, &quot;/admin/register&quot;)// 对登录注册要允许匿名访问</span><br><span class="line">                .permitAll()</span><br><span class="line">                .antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求</span><br><span class="line">                .permitAll()</span><br><span class="line">//                .antMatchers(&quot;/**&quot;)//测试时全部运行访问</span><br><span class="line">//                .permitAll()</span><br><span class="line">                .anyRequest()// 除上面外的所有请求全部需要鉴权认证</span><br><span class="line">                .authenticated();</span><br><span class="line">        // 禁用缓存</span><br><span class="line">        httpSecurity.headers().cacheControl();</span><br><span class="line">        // 添加JWT filter</span><br><span class="line">        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);</span><br><span class="line">        //添加自定义未授权和未登录结果返回</span><br><span class="line">        httpSecurity.exceptionHandling()</span><br><span class="line">                .accessDeniedHandler(restfulAccessDeniedHandler)</span><br><span class="line">                .authenticationEntryPoint(restAuthenticationEntryPoint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void configure(AuthenticationManagerBuilder auth) throws Exception &#123;</span><br><span class="line">        auth.userDetailsService(userDetailsService())</span><br><span class="line">                .passwordEncoder(passwordEncoder());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public PasswordEncoder passwordEncoder() &#123;</span><br><span class="line">        return new BCryptPasswordEncoder();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public UserDetailsService userDetailsService() &#123;</span><br><span class="line">        //获取登录用户信息</span><br><span class="line">        return username -&gt; &#123;</span><br><span class="line">            UmsAdmin admin = adminService.getAdminByUsername(username);</span><br><span class="line">            if (admin != null) &#123;</span><br><span class="line">                List&lt;UmsPermission&gt; permissionList = adminService.getPermissionList(admin.getId());</span><br><span class="line">                return new AdminUserDetails(admin,permissionList);</span><br><span class="line">            &#125;</span><br><span class="line">            throw new UsernameNotFoundException(&quot;用户名或密码错误&quot;);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter()&#123;</span><br><span class="line">        return new JwtAuthenticationTokenFilter();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Bean</span><br><span class="line">    @Override</span><br><span class="line">    public AuthenticationManager authenticationManagerBean() throws Exception &#123;</span><br><span class="line">        return super.authenticationManagerBean();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="相关依赖及方法说明"><a href="#相关依赖及方法说明" class="headerlink" title="#相关依赖及方法说明"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E7%9B%B8%E5%85%B3%E4%BE%9D%E8%B5%96%E5%8F%8A%E6%96%B9%E6%B3%95%E8%AF%B4%E6%98%8E">#</a>相关依赖及方法说明</h4><ul>
<li>configure(HttpSecurity httpSecurity)：用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器；</li>
<li>configure(AuthenticationManagerBuilder auth)：用于配置UserDetailsService及PasswordEncoder；</li>
<li>RestfulAccessDeniedHandler：当用户没有访问权限时的处理器，用于返回JSON格式的处理结果；</li>
<li>RestAuthenticationEntryPoint：当未登录或token失效时，返回JSON格式的结果；</li>
<li>UserDetailsService:SpringSecurity定义的核心接口，用于根据用户名获取用户信息，需要自行实现；</li>
<li>UserDetails：SpringSecurity定义用于封装用户信息的类（主要是用户信息和权限），需要自行实现；</li>
<li>PasswordEncoder：SpringSecurity定义的用于对密码进行编码及比对的接口，目前使用的是BCryptPasswordEncoder；</li>
<li>JwtAuthenticationTokenFilter：在用户名和密码校验前添加的过滤器，如果有jwt的token，会自行根据token信息进行登录。</li>
</ul>
<h3 id="添加RestfulAccessDeniedHandler"><a href="#添加RestfulAccessDeniedHandler" class="headerlink" title="#添加RestfulAccessDeniedHandler"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0restfulaccessdeniedhandler">#</a>添加RestfulAccessDeniedHandler</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.component;</span><br><span class="line"></span><br><span class="line">import cn.hutool.json.JSONUtil;</span><br><span class="line">import com.macro.mall.tiny.common.api.CommonResult;</span><br><span class="line">import org.springframework.security.access.AccessDeniedException;</span><br><span class="line">import org.springframework.security.web.access.AccessDeniedHandler;</span><br><span class="line">import org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line">import javax.servlet.ServletException;</span><br><span class="line">import javax.servlet.http.HttpServletRequest;</span><br><span class="line">import javax.servlet.http.HttpServletResponse;</span><br><span class="line">import java.io.IOException;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 当访问接口没有权限时，自定义的返回结果</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">public class RestfulAccessDeniedHandler implements AccessDeniedHandler&#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void handle(HttpServletRequest request,</span><br><span class="line">                       HttpServletResponse response,</span><br><span class="line">                       AccessDeniedException e) throws IOException, ServletException &#123;</span><br><span class="line">        response.setCharacterEncoding(&quot;UTF-8&quot;);</span><br><span class="line">        response.setContentType(&quot;application/json&quot;);</span><br><span class="line">        response.getWriter().println(JSONUtil.parse(CommonResult.forbidden(e.getMessage())));</span><br><span class="line">        response.getWriter().flush();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="添加RestAuthenticationEntryPoint"><a href="#添加RestAuthenticationEntryPoint" class="headerlink" title="#添加RestAuthenticationEntryPoint"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0restauthenticationentrypoint">#</a>添加RestAuthenticationEntryPoint</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.component;</span><br><span class="line"></span><br><span class="line">import cn.hutool.json.JSONUtil;</span><br><span class="line">import com.macro.mall.tiny.common.api.CommonResult;</span><br><span class="line">import org.springframework.security.core.AuthenticationException;</span><br><span class="line">import org.springframework.security.web.AuthenticationEntryPoint;</span><br><span class="line">import org.springframework.stereotype.Component;</span><br><span class="line"></span><br><span class="line">import javax.servlet.ServletException;</span><br><span class="line">import javax.servlet.http.HttpServletRequest;</span><br><span class="line">import javax.servlet.http.HttpServletResponse;</span><br><span class="line">import java.io.IOException;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * 当未登录或者token失效访问接口时，自定义的返回结果</span><br><span class="line"> * Created by macro on 2018/5/14.</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint &#123;</span><br><span class="line">    @Override</span><br><span class="line">    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException &#123;</span><br><span class="line">        response.setCharacterEncoding(&quot;UTF-8&quot;);</span><br><span class="line">        response.setContentType(&quot;application/json&quot;);</span><br><span class="line">        response.getWriter().println(JSONUtil.parse(CommonResult.unauthorized(authException.getMessage())));</span><br><span class="line">        response.getWriter().flush();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="添加AdminUserDetails"><a href="#添加AdminUserDetails" class="headerlink" title="#添加AdminUserDetails"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0adminuserdetails">#</a>添加AdminUserDetails</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.dto;</span><br><span class="line"></span><br><span class="line">import com.macro.mall.tiny.mbg.model.UmsAdmin;</span><br><span class="line">import com.macro.mall.tiny.mbg.model.UmsPermission;</span><br><span class="line">import org.springframework.security.core.GrantedAuthority;</span><br><span class="line">import org.springframework.security.core.authority.SimpleGrantedAuthority;</span><br><span class="line">import org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line"></span><br><span class="line">import java.util.Collection;</span><br><span class="line">import java.util.List;</span><br><span class="line">import java.util.stream.Collectors;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * SpringSecurity需要的用户详情</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class AdminUserDetails implements UserDetails &#123;</span><br><span class="line">    private UmsAdmin umsAdmin;</span><br><span class="line">    private List&lt;UmsPermission&gt; permissionList;</span><br><span class="line">    public AdminUserDetails(UmsAdmin umsAdmin, List&lt;UmsPermission&gt; permissionList) &#123;</span><br><span class="line">        this.umsAdmin = umsAdmin;</span><br><span class="line">        this.permissionList = permissionList;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() &#123;</span><br><span class="line">        //返回当前用户的权限</span><br><span class="line">        return permissionList.stream()</span><br><span class="line">                .filter(permission -&gt; permission.getValue()!=null)</span><br><span class="line">                .map(permission -&gt;new SimpleGrantedAuthority(permission.getValue()))</span><br><span class="line">                .collect(Collectors.toList());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String getPassword() &#123;</span><br><span class="line">        return umsAdmin.getPassword();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public String getUsername() &#123;</span><br><span class="line">        return umsAdmin.getUsername();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isAccountNonExpired() &#123;</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isAccountNonLocked() &#123;</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isCredentialsNonExpired() &#123;</span><br><span class="line">        return true;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public boolean isEnabled() &#123;</span><br><span class="line">        return umsAdmin.getStatus().equals(1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="添加JwtAuthenticationTokenFilter"><a href="#添加JwtAuthenticationTokenFilter" class="headerlink" title="#添加JwtAuthenticationTokenFilter"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E6%B7%BB%E5%8A%A0jwtauthenticationtokenfilter">#</a>添加JwtAuthenticationTokenFilter</h3><blockquote>
<p>在用户名和密码校验前添加的过滤器，如果请求中有jwt的token且有效，会取出token中的用户名，然后调用SpringSecurity的API进行登录操作。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">package com.macro.mall.tiny.component;</span><br><span class="line"></span><br><span class="line">import com.macro.mall.tiny.common.utils.JwtTokenUtil;</span><br><span class="line">import org.slf4j.Logger;</span><br><span class="line">import org.slf4j.LoggerFactory;</span><br><span class="line">import org.springframework.beans.factory.annotation.Autowired;</span><br><span class="line">import org.springframework.beans.factory.annotation.Value;</span><br><span class="line">import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;</span><br><span class="line">import org.springframework.security.core.context.SecurityContextHolder;</span><br><span class="line">import org.springframework.security.core.userdetails.UserDetails;</span><br><span class="line">import org.springframework.security.core.userdetails.UserDetailsService;</span><br><span class="line">import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;</span><br><span class="line">import org.springframework.web.filter.OncePerRequestFilter;</span><br><span class="line"></span><br><span class="line">import javax.servlet.FilterChain;</span><br><span class="line">import javax.servlet.ServletException;</span><br><span class="line">import javax.servlet.http.HttpServletRequest;</span><br><span class="line">import javax.servlet.http.HttpServletResponse;</span><br><span class="line">import java.io.IOException;</span><br><span class="line"></span><br><span class="line">/**</span><br><span class="line"> * JWT登录授权过滤器</span><br><span class="line"> * Created by macro on 2018/4/26.</span><br><span class="line"> */</span><br><span class="line">public class JwtAuthenticationTokenFilter extends OncePerRequestFilter &#123;</span><br><span class="line">    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);</span><br><span class="line">    @Autowired</span><br><span class="line">    private UserDetailsService userDetailsService;</span><br><span class="line">    @Autowired</span><br><span class="line">    private JwtTokenUtil jwtTokenUtil;</span><br><span class="line">    @Value(&quot;$&#123;jwt.tokenHeader&#125;&quot;)</span><br><span class="line">    private String tokenHeader;</span><br><span class="line">    @Value(&quot;$&#123;jwt.tokenHead&#125;&quot;)</span><br><span class="line">    private String tokenHead;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    protected void doFilterInternal(HttpServletRequest request,</span><br><span class="line">                                    HttpServletResponse response,</span><br><span class="line">                                    FilterChain chain) throws ServletException, IOException &#123;</span><br><span class="line">        String authHeader = request.getHeader(this.tokenHeader);</span><br><span class="line">        if (authHeader != null &amp;&amp; authHeader.startsWith(this.tokenHead)) &#123;</span><br><span class="line">            String authToken = authHeader.substring(this.tokenHead.length());// The part after &quot;Bearer &quot;</span><br><span class="line">            String username = jwtTokenUtil.getUserNameFromToken(authToken);</span><br><span class="line">            LOGGER.info(&quot;checking username:&#123;&#125;&quot;, username);</span><br><span class="line">            if (username != null &amp;&amp; SecurityContextHolder.getContext().getAuthentication() == null) &#123;</span><br><span class="line">                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);</span><br><span class="line">                if (jwtTokenUtil.validateToken(authToken, userDetails)) &#123;</span><br><span class="line">                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());</span><br><span class="line">                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));</span><br><span class="line">                    LOGGER.info(&quot;authenticated user:&#123;&#125;&quot;, username);</span><br><span class="line">                    SecurityContextHolder.getContext().setAuthentication(authentication);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        chain.doFilter(request, response);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="项目源码地址"><a href="#项目源码地址" class="headerlink" title="#项目源码地址"></a><a target="_blank" rel="noopener" href="https://www.macrozheng.com/mall/architect/mall_arch_04.html#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80">#</a>项目源码地址</h2><p><a target="_blank" rel="noopener" href="https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-04">https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-04</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io">十一星野</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://ko25891wan.gitlab.io/2024/01/52c2363b5c0f.html">https://ko25891wan.gitlab.io/2024/01/52c2363b5c0f.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://ko25891wan.gitlab.io" target="_blank">小小程序员</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2024/01/e7542e90d72c.html" title="mall整合SpringSecurity和JWT实现认证和授权（二）"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">mall整合SpringSecurity和JWT实现认证和授权（二）</div></div></a></div><div class="next-post pull-right"><a href="/2024/01/a4e49a7541a0.html" title="mall整合Swagger-UI实现在线API文档"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">mall整合Swagger-UI实现在线API文档</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://qiniu.ko25891wan.top/%E6%97%A5%E8%AE%B0%E8%BD%AF%E4%BB%B6/%E5%A4%B4%E5%83%8F/%E7%81%B0%E5%A4%AA%E7%8B%BC.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">十一星野</div><div class="author-info__description">归途也还可爱</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">120</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">4</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">22</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="https://gitlab.com/ko25891wan/ko25891wan.gitlab.io" target="_blank" title="Gitlab"><i class="fab fa-gitlab" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:ko25891wan@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%F0%9F%91%8D-%E7%9B%B8%E5%85%B3%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">👍 相关视频教程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E4%BD%BF%E7%94%A8%E6%A1%86%E6%9E%B6%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.</span> <span class="toc-text">项目使用框架介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#SpringSecurity"><span class="toc-number">2.1.</span> <span class="toc-text">SpringSecurity</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JWT"><span class="toc-number">2.2.</span> <span class="toc-text">JWT</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#JWT%E7%9A%84%E7%BB%84%E6%88%90"><span class="toc-number">2.2.1.</span> <span class="toc-text">JWT的组成</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JWT%E5%AE%9E%E4%BE%8B"><span class="toc-number">2.2.2.</span> <span class="toc-text">JWT实例</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#JWT%E5%AE%9E%E7%8E%B0%E8%AE%A4%E8%AF%81%E5%92%8C%E6%8E%88%E6%9D%83%E7%9A%84%E5%8E%9F%E7%90%86"><span class="toc-number">2.2.3.</span> <span class="toc-text">JWT实现认证和授权的原理</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Hutool"><span class="toc-number">2.3.</span> <span class="toc-text">Hutool</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E4%BD%BF%E7%94%A8%E8%A1%A8%E8%AF%B4%E6%98%8E"><span class="toc-number">3.</span> <span class="toc-text">项目使用表说明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B4%E5%90%88SpringSecurity%E5%8F%8AJWT"><span class="toc-number">4.</span> <span class="toc-text">整合SpringSecurity及JWT</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9C%A8pom-xml%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%A1%B9%E7%9B%AE%E4%BE%9D%E8%B5%96"><span class="toc-number">4.1.</span> <span class="toc-text">在pom.xml中添加项目依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0JWT-token%E7%9A%84%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">4.2.</span> <span class="toc-text">添加JWT token的工具类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0SpringSecurity%E7%9A%84%E9%85%8D%E7%BD%AE%E7%B1%BB"><span class="toc-number">4.3.</span> <span class="toc-text">添加SpringSecurity的配置类</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E4%BE%9D%E8%B5%96%E5%8F%8A%E6%96%B9%E6%B3%95%E8%AF%B4%E6%98%8E"><span class="toc-number">4.3.1.</span> <span class="toc-text">相关依赖及方法说明</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0RestfulAccessDeniedHandler"><span class="toc-number">4.4.</span> <span class="toc-text">添加RestfulAccessDeniedHandler</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0RestAuthenticationEntryPoint"><span class="toc-number">4.5.</span> <span class="toc-text">添加RestAuthenticationEntryPoint</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0AdminUserDetails"><span class="toc-number">4.6.</span> <span class="toc-text">添加AdminUserDetails</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0JwtAuthenticationTokenFilter"><span class="toc-number">4.7.</span> <span class="toc-text">添加JwtAuthenticationTokenFilter</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E6%BA%90%E7%A0%81%E5%9C%B0%E5%9D%80"><span class="toc-number">5.</span> <span class="toc-text">项目源码地址</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/c60470b9a892.html" title="Java集合使用注意事项总结">Java集合使用注意事项总结</a><time datetime="2024-02-03T04:58:22.000Z" title="发表于 2024-02-03 12:58:22">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/02/81fb7a201f29.html" title="无题">无题</a><time datetime="2024-02-03T03:15:31.812Z" title="发表于 2024-02-03 11:15:31">2024-02-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/5737c1ec69a9.html" title="Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)">Wed Jan 17 2024 00:00:00 GMT+0800 (中国标准时间)</a><time datetime="2024-01-31T06:56:16.000Z" title="发表于 2024-01-31 14:56:16">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/f510db7d2f19.html" title="Spring常见面试题总结">Spring常见面试题总结</a><time datetime="2024-01-31T06:55:58.000Z" title="发表于 2024-01-31 14:55:58">2024-01-31</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2024/01/9be065e9f288.html" title="redis 面试">redis 面试</a><time datetime="2024-01-31T06:55:55.000Z" title="发表于 2024-01-31 14:55:55">2024-01-31</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2024 By 十一星野</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.staticfile.org/fancyapps-ui/5.0.32/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.staticfile.org/instant.page/5.2.0/instantpage.min.js" type="module"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>